from django import oldforms

from django.core.validators import ValidationError

class AudioUploadField(oldforms.FileUploadField):
    "A FileUploadField that raises CriticalValidationError if the uploaded file isn't audio."
    def __init__(self, *args, **kwargs):
        oldforms.FileUploadField.__init__(self, *args, **kwargs)
        self.validator_list.insert(0, is_valid_audio)

def is_valid_image(field_data, all_data):
    """
    Checks that the file-upload field data contains a valid audio file
    (MP3, OGG, M4A, possibly others -- whatever mutagen supports).
    """
    import mutagen
    from cStringIO import StringIO
    try:
        content = field_data['content']
    except TypeError:
        raise CriticalValidationError, _("No file was submitted. Check the encoding type on the form.")
    if not mutagen.File(StringIO(content)):
        raise CriticalValidationError, _("Upload a valid audio file. The file you uploaded was either not audio or corrupted audio.")

